/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useEffect, useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProForm, { ProFormText, ProFormSelect } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { Button, Form, message, Select, Space, Modal, Row, Col, Divider } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-form';
import { tableItem, columns } from './index.d';
import { getAllUsers, getDepartments, getUserListAsync } from '@/services/admin/editMenu';
import { connect, useSelector } from 'umi';
import type { Dispatch } from 'umi';
import type { ConnectState } from '@/models/connect';
import DragTable from '@/components/DragTable';
import isString from 'lodash/isString';
import { expandRoutes } from '@/utils/admin/menu';
import type { BasicLayoutProps as ProLayoutProps } from '@ant-design/pro-layout';
import { callback, getAuthDetailList } from '@/utils/admin/menu/index';
import Role from '@/components/_page/admin/menu/role';
import styles from './index.less';

interface AdminMenuProps extends ProLayoutProps {
  routes: any[];
  currentUser: any;
  dispatch?: Dispatch;
}

const { Option } = Select;
const AdminMenu: React.FC<AdminMenuProps> = (props) => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const {
    dispatch,
    routes,
    history,
    currentUser: { managerInfo, isManager },
  } = props;
  const authorityRoutes = expandRoutes(routes[1]?.routes[0]?.routes);
  const formRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [options, setOptions] = useState<any>([{ label: '快宝网络', value: '1' }]);
  const [defdataSource, setDefDataSource] = useState<any[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [upDateManagerName, setUpDateManagerName] = useState<string>('');
  const [menuList, setMenuList] = useState<string[]>([]);
  const [spin, setSpin] = useState<boolean>(false);

  const getDepartmentList = useCallback(
    () =>
      getDepartments({}).then((res) =>
        callback(res, {
          cb: (data: any) => {
            data.map((item: any) => ((item.label = item.name), (item.value = item.department_id)));
            setOptions(data);
          },
          messageMsg: false,
        }),
      ),
    [],
  );

  const getUserList = useCallback(async (cb) => {
    const { data = [] } = await getAllUsers({});
    setDefDataSource(data);
    setDataSource(data);
    if (cb && typeof cb === 'function') {
      cb(data);
    }
  }, []);

  const tableReload = () => {
    getUserList(() => {
      formRef.current?.submit();
    });
  };

  const RoleCallback = useCallback(() => {
    tableReload();
  }, []);

  useEffect(() => {
    getDepartmentList();
    getUserList(() => {});
  }, []);

  const search = ({ type, val, data, cb }: any) => {
    let sourceData: any = [];
    if (type == 'mobile' || type == 'name') {
      sourceData = data.filter((item: any) => `${item[type]}`.includes(val));
    } else {
      const actionList = `${val}`.split('、');
      const len = actionList.length;
      sourceData = data.filter((item: any) => {
        if (item.menu_list.length >= len) {
          const menu_list = getAuthDetailList(authorityRoutes, item.menu_list.map(Number)).split(
            ',',
          );
          return menu_list
            .map((item1: any) => actionList.map((item2: any) => item1.includes(item2)))
            .map((item3: any) => item3.includes(true))
            .includes(true);
        } else {
          return false;
        }
      });
    }
    if (cb && typeof cb === 'function') {
      cb(sourceData);
    }
  };

  const onSubmit = (values: any) => {
    setSubmitting(true);
    const { department, type, val } = values;
    const [depa = { name: '' }] = options.filter((item: any) => item.value == department);
    if (depa.name == '快宝网络') {
      if (type && val) {
        search({ type, val, data: defdataSource, cb: (data: any) => setDataSource(data) });
      } else {
        setDataSource(defdataSource);
      }
    } else if (type && val) {
      const departmentData = defdataSource.filter((item: any) =>
        item.department_list.map((item1: any) => item1.name).includes(depa.name),
      );
      search({ type, val, data: departmentData, cb: (data: any) => setDataSource(data) });
    } else {
      const departmentData = defdataSource.filter((item: any) =>
        item.department_list.map((item1: any) => item1.name).includes(depa.name),
      );
      setDataSource(departmentData);
    }
    setSubmitting(false);
  };

  const uploadUserList = () => {
    if (spin) return;
    setSpin(true);
    getUserListAsync().then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success(msg);
        RoleCallback();
        setSpin(false);
      } else {
        message.error(msg);
      }
    });
  };

  const allAddAuth = (userid: string) => {
    if (!isManager) {
      message.error(`请联系管理员${managerInfo.name}添加权限`);
      return;
    } else {
      const url = isString(userid) ? `/f/admin/menu/edit?userid=${userid}` : '/f/admin/menu/edit';
      history?.push(url);
    }
  };

  const updateManager = ({ name }: any) => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
        payload: {
          type: 'updateManager',
          callBack: () => {
            setUpDateManagerName(name);
            setVisible(true);
          },
        },
      });
    }
  };

  const handleOk = () => {
    setVisible(false);
    history?.push('/');
  };

  const handleCancel = () => {
    setVisible(false);
    setMenuList([]);
  };

  const handleMenuList = (data: any[]) => {
    setMenuList(data);
    setVisible(true);
  };

  const prefixSelector = (
    <Form.Item name='type' noStyle>
      <Select style={{ width: 100 }}>
        <Option value='name'>姓名</Option>
        <Option value='mobile'>手机号</Option>
        <Option value='jurisdiction'>功能</Option>
      </Select>
    </Form.Item>
  );

  return (
    <PageContainer className={styles.menu} title={false}>
      <Role updateManager={updateManager} params={{ managerInfo, isManager }}></Role>
      <Divider />
      <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
        <ProForm
          formRef={formRef}
          layout='inline'
          onFinish={onSubmit}
          initialValues={{
            department: '1',
            type: 'name',
          }}
          submitter={{
            render: (form_props) => {
              return [
                <Button
                  loading={submitting}
                  type='primary'
                  key='submit'
                  onClick={() => form_props.form?.submit?.()}
                >
                  查询
                </Button>,
                <Button
                  loading={submitting}
                  key='submit'
                  onClick={() => {
                    form_props.form?.resetFields();
                    form_props.form?.submit?.();
                  }}
                >
                  重置
                </Button>,
                <div>
                  <Button loading={submitting} type='primary' key='submit' onClick={allAddAuth}>
                    批量授权
                  </Button>
                  <a className={styles.menu__reload} key='submit' onClick={uploadUserList}>
                    <ReloadOutlined spin={spin} />
                  </a>
                </div>,
              ];
            },
          }}
        >
          <ProFormSelect allowClear={false} options={options} name='department' label='部门选择' />
          <ProFormText
            className={styles.menu_input}
            label='请查询类型类型'
            name='val'
            addonBefore={prefixSelector}
            placeholder='姓名/手机号/功能'
          />
        </ProForm>
      </Space>
      <DragTable>
        <ProTable<tableItem>
          pagination={false}
          rowKey='id'
          dataSource={dataSource}
          columns={columns(authorityRoutes, allAddAuth, handleMenuList)}
          search={false}
          options={false}
          scroll={{ x: 640 }}
        />
      </DragTable>
      <Modal
        title={menuList.length > 0 ? '已授权功能信息' : '转让管理员信息'}
        visible={visible}
        keyboard={false}
        maskClosable={false}
        closable={false}
        footer={[
          <Button
            type='primary'
            key='goBack'
            size='middle'
            onClick={menuList.length > 0 ? handleCancel : handleOk}
          >
            确定
          </Button>,
        ]}
      >
        {menuList.length > 0 ? (
          menuList
        ) : (
          <Row>
            <Col>转让人：</Col>
            <Col>{upDateManagerName}</Col>
          </Row>
        )}
      </Modal>
    </PageContainer>
  );
};

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(React.memo(AdminMenu));
